﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WebSocket4Net;

namespace Chat
{
    /// <summary>
    /// Register.xaml 的交互逻辑
    /// </summary>
    public partial class Register : Window
    {
        public WebSocket webSocket;
        public long id;
        public Register(string host)
        {
            InitializeComponent();
            Header.MouseLeftButtonDown += (sender, e) => DragMove();
            Height = Math.Max(SystemParameters.PrimaryScreenHeight / 3 * 2, 350);
            Width = SystemParameters.PrimaryScreenWidth / 3;
            webSocket = new WebSocket(host);
            webSocket.Open();
        }

        private void ProcessEmail(object sendeer, MessageReceivedEventArgs e)
        {
            string[] m = e.Message.Split('\n');
            if (m[0] == "Register")
            {
                if (m[1] == "SendEmail")
                {
                    MessageBox.Show("邮件已发送，如未收到请检查邮箱垃圾箱");
                }
                if (m[1] == "EmailSent")
                {
                    MessageBox.Show("邮件发送冷却，请过几分钟再来，这期间验证码持续有效");
                }
                if (m[1] == "Success")
                {
                    webSocket.MessageReceived -= ProcessEmail;
                    MessageBox.Show("注册成功，自动记住密码");
                    File.WriteAllText("UserData", m[3] + "\n" + "{#hadSHA512}" + Protocol.sha512Encode(Password.Text));
                    id = Convert.ToInt64(m[3]);
                    Close();
                }
            }
        }

        private void Register_Load(object sender, EventArgs e)
        {

        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }


        private void Register_Clicked(object sender, RoutedEventArgs e)
        {
            if (Password.Text != Password_2.Text)
            {
                MessageBox.Show("两次输入的密码不一样，请检查");
                return;
            }
            webSocket.Send("Register\n" + Verify_Code.Text + "\n\n" + new JObject { { "username", Account.Text }, { "password", Password.Text } });
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            webSocket.Send("Register\n" + Email.Text + "\n\n");
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Method.LogoutExit(webSocket);
        }

        private void Goto_Login(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
